/**
 * created by dpf
 * 图斑分析
 */
define([
  'dojo/_base/declare',
  'dojo/_base/html',
  'dojo/query',
  'dojo',
  'dojo/aspect',
  'dojo/on',
  'dojo/dom',
  'dojo/dom-style',
  'dojo/_base/Color',
  'dojo/_base/lang',
  'dojo/_base/xhr',
  'dojo/_base/array',
  'dojo/dom-construct',
  'dojo/_base/json',
  'dojo/data/ItemFileWriteStore',
  'dojox/grid/DataGrid',
  './common',
  'esri/toolbars/draw',
  'esri/graphic',
  'esri/layers/GraphicsLayer',
  "esri/layers/ArcGISDynamicMapServiceLayer",
  'esri/symbols/SimpleLineSymbol',
  'esri/symbols/SimpleFillSymbol',
  'esri/symbols/SimpleMarkerSymbol',
  'esri/geometry/Point',
  'esri/geometry/Multipoint',
  'esri/geometry/Polygon',
  'esri/geometry/Extent',
  'esri/SpatialReference',

  "esri/tasks/query", "esri/tasks/QueryTask",

  'dijit/_WidgetsInTemplateMixin',
  'dijit/layout/TabContainer',
  'dijit/layout/ContentPane',
  'dijit/form/Button',
  'dijit/registry',
  'jimu/BaseWidget',
  'jimu/dijit/Message',
  'jimu/dijit/AppStatePopup',
  './LoadingIndicator',
  'libs/echarts/echarts',
  'libs/proj4js/dist/proj4',
],
  function (declare, html, query, dojo, aspect, on, dom, domStyle, Color, lang, xhr, array, domConstruct, json,
    ItemFileWriteStore, DataGrid, common, Draw, Graphic, GraphicsLayer, ArcGISDynamicMapServiceLayer, SimpleLineSymbol, SimpleFillSymbol,
    SimpleMarkerSymbol, Point, Multipoint, Polygon, Extent,SpatialReference, Query, QueryTask,
    _WidgetsInTemplateMixin, TabContainer,
    ContentPane, Button, registry, BaseWidget, Message, AppStatePopup, LoadingIndicator, echarts, proj4) {
    var clazz = declare([BaseWidget, _WidgetsInTemplateMixin], {
      baseClass: 'jimu-widget-analysis',
      toolbar: null,
      map: null,
      lyrIncidents: null,
      incident: null,
      resEchart: null,
      names: [],
      nameDataes: [],
      dictionaryTable: [],
      echart: undefined,
      loading: null,
      tableData: {
        identifier: 'id',
        items: []
      },
      loadingNode: null,
      graphicPiont: null,
      incidentPiont: null,
      num: 0,
      symPoly: null,
      incidentPoly: [],
      graphicPolyon: null,
      polyGraphic: null,
      button2: null,
      button1: null,
      coordsList: {
        identifier: 'id',
        items: []
      },
      rowData: null,
      containerTab: null,
      appConfig: null,
      config:null,
      projection: [
        {
          wkid: 4326,
          proj4: '+proj=longlat +datum=WGS84 +no_def'
        },
        {
          wkid: 4490,
          proj4: '+proj=longlat +ellps=GRS80 +no_defs'
        },
        {
          wkid: 3857,
          proj4: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs'
        }
      ],
      proj: null,
      url: 'http://118.31.43.251:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer/intersect',
      coordsStore: null,
      option: null,
      // query task and query for parcels
      qtUrl: "",
      queryTask: null,
      query: null,
      qtGeometryType: null,
      postCreate: function () {
        this.inherited(arguments)
      },
      constructor: function ( /*Object*/ options, mapDivId) {
        console.log(options)
        this.appConfig = options.appConfig
        this.config = options.config
        this._getProjection()
      },
      startup: function () {
        // this.map.getExen
        this.inherited(arguments)
        this.map.centerAndZoom([0.05534044758312709, 0.025630269688248296], 12)
        this.containerTab = dom.byId('containerTab')
        var $that = this
        // select echart tab event
        
        this._loadUI()
        this.dictionaryTable = this.getDictionaryTable()
        this.symPoly = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
          new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT,
            new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25])
        )
        this.graphicPolyon = new GraphicsLayer()
        this.graphicPiont = new GraphicsLayer()

        // srhee
        

        this.map.on('click', e => {
          console.log(e)
        })
      },
      onClose:function(){
        registry.byId("containerTab").destroy();
        this._clear()
      },
      // 节点的渲染
      _loadUI: function () {
        // 绑定监听事件
        this.toolbar = new Draw(this.map, {
          tooltipOffset: 20,
          drawTime: 90
        })
        this.toolbar.on('draw-end', lang.hitch(this, this._drawIncident))

        // add srhee
        // let htmlselect = '<option value="" geometryType="">请下拉选择!</option>';
        // console.log(this.appConfig)
        // this.config.layers.forEach((item)=>{
        //   htmlselect += `<option value="${item.uri}" geometryType="${item.geometryType}">${item.name}</option>`
        // })
        // document.getElementById("layerToQuery").innerHTML = htmlselect
        // console.log($);
        // $("#layerToQuery").on('change' , (e)=>{
        //   console.log(e)
        //   var obj = document.getElementById('layerToQuery'); // 定位id
        //   var index = obj.selectedIndex; // 选中索引
        //   this.qtUrl = obj.options[index].value; // 选中值
        //   this.qtGeometryType = obj.options[index].getAttribute('geometryType');
        // })
      },
      // 手绘面
      _drawPolygon: function () {
        this.toolbar.activate(Draw.POLYGON)
        this.disableWebMapPopup()
      },
      // 点选
      _drawPoint: function () {
        console.log(this.qtGeometryType)
        if (this.qtUrl === '' || !this.qtGeometryType) {
          alert('请先选择带查询图层!')
        }else{
          this.toolbar.activate(Draw.POINT)
          this.disableWebMapPopup()
        }
      },
      /**
       * 清除绘面
       * @private
       */
      _clearPoly: function () {
        this.map.graphics.clear()

        if (this.lyrIncidents !== null) {
          this.lyrIncidents.clear()
          this.incident = null
          this.toolbar.deactivate()
        }

        if (this.graphicPolyon !== null) {
          this.graphicPolyon.clear()
          this.polyGraphic = null
        }

        this.loading = null
      },
      /**
       * 清除事件
       * @private
       */
      _clear: function () {
        this.num = 0
        if (this.graphicPiont !== null) {
          this.graphicPiont.clear()
          this.incidentPiont = null
        }

        this._clearPoly()
      },
      /**
       * draw incidents
       * @param evt
       * @private
       */
      // srhee
      _drawIncident: function (evt) {
        console.log(evt);
        this.lyrIncidents = new GraphicsLayer()
        this.incident = new Graphic(evt.geometry, this.symPoly)
        this.lyrIncidents.add(this.incident)
        try {
          this.map.addLayer(this.lyrIncidents)
          this.map.setExtent(this.incident._extent)
          this._doIntersectAnalysis(this.incident.geometry)
        } catch (e) {
          console.error(e)
        }
        this.toolbar.deactivate()
      },
      disableWebMapPopup: function () {
        if (this.map) {
          this.map.setInfoWindowOnClick(false)
        }
      },
      /**
       * 相交分析
       * @param geom
       * @private
       */
      // srhee
      _doIntersectAnalysis(geom) {
        var node = domConstruct.create('div')

        domStyle.set(node, {
          'min-height': '450px',
          'max-width': '300px'
        })
        this.loading = new LoadingIndicator()

        this.loading.show()
        let promises = [];
        this.config.layers.forEach(layerConfig=>{
          const {name,uri,geometryType} = layerConfig
          let queryTask = new QueryTask(uri);
          let query = new Query();
          query.returnGeometry = true;
          query.outFields = ["*"];
          query.geometry = geom;
          let promise = queryTask.execute(query);
          promises.push(promise)
          
        })

        Promise.all(promises).then(lang.hitch(this, this.handleQueryResults))
      },
      handleQueryResults(results) {
        console.log("queries finished: ", results);
        let attrHtml = ``
        results.forEach((item,index)=>{
          let features = item.features;
          let totalNum = features.length,
          totalLength = 0,
          totalArea = 0;
          if(item.geometryType === "esriGeometryPoint"){ // 计算个数
            attrHtml += `<div style="padding:10px;border:1px solid #ccc" class="_showGraphics" index="${index}">
            <div><b>图层名:</b><span>${this.config.layers[index].name}</span></div>
            <div><b>图层几何类型:</b><span>${this.config.layers[index].geometryType}</span></div>
            <div><b>统计个数(个):</b><span>${totalNum}</span></div>
            </div>`
          }else if(item.geometryType === "esriGeometryPolyline"){ // 计算个数 总长度
            features.forEach(fea=>{
              var geo = esri.geometry.webMercatorToGeographic(fea.geometry);
              var length = esri.geometry.geodesicLengths([geo], esri.Units.METERS);
              if(!isNaN(length[0]))
                totalLength += length[0];
            })
            attrHtml += `<div style="padding:10px;border:1px solid #ccc" class="_showGraphics" index="${index}">
            <div><b>图层名:</b><span>${this.config.layers[index].name}</span></div>
            <div><b>图层几何类型:</b><span>${this.config.layers[index].geometryType}</span></div>
            <div><b>统计个数(个):</b><span>${totalNum}</span></div>
            <div><b>统计总长度(米):</b><span>${totalLength}</span></div>
            </div>`
          }else if(item.geometryType === "esriGeometryPolygon"){ // 个数 总面积
            features.forEach(fea=>{
              var geo = esri.geometry.webMercatorToGeographic(fea.geometry);
              var area = esri.geometry.geodesicAreas([geo], esri.Units.SQUARE_METERS);
              if(!isNaN(area[0]))
                totalArea += area[0];
            })
            attrHtml += `<div style="padding:10px;border:1px solid #ccc" class="_showGraphics" index="${index}">
            <div><b>图层名:</b><span>${this.config.layers[index].name}</span></div>
            <div><b>图层几何类型:</b><span>${this.config.layers[index].geometryType}</span></div>
            <div><b>统计个数(个):</b><span>${totalNum}</span></div>
            <div><b>统计总面积(平方米):</b><span>${totalArea}</span></div>
            </div>`
          }
          console.log(totalArea,totalLength,totalNum)
        })
        $("#gridDiv").html(attrHtml);
        let that = this;
        $("._showGraphics").click(function(){
          let index = $(this).attr("index")
          that._showGraphics(results[index].features, that.config.layers[index].geometryType)
        })
      },
      _showGraphics(features, type) {
        // add the results to the map
        this.map.graphics.clear();
        let symbol;
        switch ( type ){
          case 'polyline':
            symbol = new SimpleLineSymbol(
              SimpleLineSymbol.STYLE_DASH,
              new Color([255,0,0]),
              3
            );
            break;
          case 'point':
            symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 10,
              new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
              new Color([255,0,0]), 1),
              new Color([0,255,0,0.25]));
            break;
          case 'polygon':
            symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
              new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT,
              new Color([255,0,0]), 2),new Color([255,255,0,0.25])
            );
            break;
          default:
            break
        }
        let attrHtml=''
        array.forEach(features, (feat) =>{
          feat.setSymbol(symbol);
          this.map.graphics.add(feat);

          Object.keys(feat.attributes).forEach(function(key) {
            attrHtml += `<div><b>${key}:</b><span>${feat.attributes[key]}</span></div>`
          })
          attrHtml += '<hr />'
        });
        
        $("#gridCoords").html(attrHtml);
      },

      /**
       * 相同数据转换
       * @param val
       * @returns {Array}
       * @private
       */
      _mergeData(val) {
        var data = val.features
        if (val.type === 'FeatureCollection') {
          var map = {}
          var arr = []
          for (var i = 0; i < data.length; i++) {
            var di = data[i]
            var n = di.properties.TDYTQLXDM
            if (!map[n]) {
              map[n] = di.properties.SHAPE_AREA
              arr.push(di)
            } else {
              for (var j = 0; j < arr.length; j++) {
                var aj = arr[j]
                if (aj.properties.TDYTQLXDM === n) {
                  aj.properties.SHAPE_AREA += di.properties.SHAPE_AREA
                  break
                }
              }
            }
          }
          return arr
        }
      },
      /**
       * 字典表
       * @returns {*[]}
       */
      getDictionaryTable() {
        return [{
          number: '010',
          label: '基本农田保护区'
        },
        {
          number: '020',
          label: '一般农地区'
        },
        {
          number: '030',
          label: '城镇建设用地区'
        },
        {
          number: '040',
          label: '村镇建设用地区'
        },
        {
          number: '050',
          label: '独立工矿用地区'
        },
        {
          number: '060',
          label: '风景旅游用地区'
        },
        {
          number: '070',
          label: '生态环境安全控制区'
        },
        {
          number: '080',
          label: '自然与文化遗产保护区'
        },
        {
          number: '090',
          label: '林业用地区'
        },
        {
          number: '100',
          label: '牧业用地区'
        },
        {
          number: '990',
          label: '其他用地区'
        }
        ]
      },
      /**
       * 获取坐标系
       * @private
       */
      _getProjection() {
        var wkid = this.appConfig.map.mapOptions.extent.spatialReference.wkid
        this.proj = array.filter(this.projection, function (crs) {
          return wkid === crs.wkid
        })
      },
      /**
       * 坐标转换
       * @param coord
       * @returns {*}
       */
      transformTo4490: function (coord) {
        var proj = this.proj[0].proj4
        var proj4490 = '+proj=longlat +ellps=GRS80 +no_defs'
        return proj4(proj, proj4490, coord)
      }
    })

    return clazz
  })
